package com.nanrui.mutualinductor.ui.page;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.nanrui.mutualinductor.R;

public class BlueTestActivity extends Activity implements OnClickListener {
    private final static String TAG = "MainActivity";
    private BluetoothAdapter mBluetoothAdapter;
    private int REQUEST_ENABLE_BT = 1;
    private Context mContext;

    private Button mBtnBluetoothConnect;
    private Button mBtnBluetoothVisibility;
    private Button mBtnBluetoohDisconnect;
    private Button mBtnSendMessage;
    private EditText mEdttMessage;

    private TextView mTvChat;
    private ProgressDialog mProgressDialog;
    private BluetoothChatUtil mBlthChatUtil;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothChatUtil.STATE_CONNECTED:
                    String deviceName = msg.getData().getString(BluetoothChatUtil.DEVICE_NAME);
                    mBtnBluetoothConnect.setText("已成功连接到设备" + deviceName);
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    break;
                case BluetoothChatUtil.STATAE_CONNECT_FAILURE:
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothChatUtil.MESSAGE_DISCONNECTED:
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    mBtnBluetoothConnect.setText("与设备断开连接");
                    break;
                case BluetoothChatUtil.MESSAGE_READ:
                    byte[] buf = msg.getData().getByteArray(BluetoothChatUtil.READ_MSG);
                    String str = new String(buf, 0, buf.length);
                    Toast.makeText(getApplicationContext(), "读成功" + str, Toast.LENGTH_SHORT).show();

                    mTvChat.setText(mTvChat.getText().toString() + "\n" + str);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_test);
        mContext = this;
        initView();
        initBluetooth();
        mBlthChatUtil = BluetoothChatUtil.getInstance(mContext);
        mBlthChatUtil.registerHandler(mHandler);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        if (mBlthChatUtil != null) {
            // 只有国家是state_none，我们知道，我们还没有开始
            if (mBlthChatUtil.getState() == BluetoothChatUtil.STATE_NONE) {
                // 启动蓝牙聊天服务
                mBlthChatUtil.start();
            } else if (mBlthChatUtil.getState() == BluetoothChatUtil.STATE_CONNECTED) {
                BluetoothDevice device = mBlthChatUtil.getConnectedDevice();
                if (null != device && null != device.getName()) {
                    mBtnBluetoothConnect.setText("已成功连接到设备" + device.getName());
                } else {
                    mBtnBluetoothConnect.setText("已成功连接到设备");
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        unregisterReceiver(mBluetoothReceiver);
    }

    private void initView() {
        mBtnBluetoothConnect = (Button) findViewById(R.id.btn_blth_connect);
        mBtnBluetoothVisibility = (Button) findViewById(R.id.btn_blth_visiblity);
        mBtnBluetoohDisconnect = (Button) findViewById(R.id.btn_blth_disconnect);
        mBtnSendMessage = (Button) findViewById(R.id.btn_sendmessage);
        mEdttMessage = (EditText) findViewById(R.id.edt_message);
        mTvChat = (TextView) findViewById(R.id.tv_chat);

        mBtnBluetoothConnect.setOnClickListener(this);
        mBtnBluetoothVisibility.setOnClickListener(this);
        mBtnBluetoohDisconnect.setOnClickListener(this);
        mBtnSendMessage.setOnClickListener(this);
        mProgressDialog = new ProgressDialog(this);
    }

    private void initBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {//设备不支持蓝牙
            Toast.makeText(getApplicationContext(), "设备不支持蓝牙", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        //判断蓝牙是否开启
        if (!mBluetoothAdapter.isEnabled()) {//蓝牙未开启
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            //mBluetoothAdapter.enable();此方法直接开启蓝牙，不建议这样用。
        }
        //
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBluetoothReceiver, filter);
        if (mBluetoothAdapter.isEnabled()) {
            int nMode = mBluetoothAdapter.getScanMode();
            if (nMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE) {
                Log.e(TAG, "getScanMode = SCAN_MODE_CONNECTABLE");
            }
            if (nMode == BluetoothAdapter.SCAN_MODE_NONE) {
                Log.e(TAG, "getScanMode = SCAN_MODE_NONE");
            }
            if (nMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                Log.e(TAG, "getScanMode = SCAN_MODE_CONNECTABLE_DISCOVERABLE");
            }
            if (nMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(discoverableIntent);
            }
        }
        String name = mBluetoothAdapter.getName();
        String address = mBluetoothAdapter.getAddress();
        Log.d(TAG, "bluetooth name =" + name + " address =" + address);
//		Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
//		Log.d(TAG, "bonded device size ="+devices.size());
//		for(BluetoothDevice bonddevice:devices){
//			Log.d(TAG, "bonded device name ="+bonddevice.getName()+" address"+bonddevice.getAddress());
//		}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult request=" + requestCode + " result=" + resultCode);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {

            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.btn_blth_connect:

//                if (mBlthChatUtil.getState() == BluetoothChatUtil.STATE_CONNECTED) {
//                    Toast.makeText(mContext, "蓝牙已连接", Toast.LENGTH_SHORT).show();
//                } else {
//                    Set<BluetoothDevice> device = mBluetoothAdapter.getBondedDevices();
//
//                    if (device.size() > 0) { //存在已经配对过的蓝牙设备
//                        for (Iterator<BluetoothDevice> it = device.iterator(); it.hasNext(); ) {
//                            BluetoothDevice btd = it.next();
//                            String name = btd.getName();
//                            String address = btd.getAddress();
//                            String nameString = btd.getName() + '\n' + btd.getAddress();
//                            Log.e(TAG, nameString);
//                            if (address != null && address.startsWith("98")) {
//                                mBlthChatUtil.connect(btd);
//                                Toast.makeText(mContext, "连接成功", Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                    } else {  //不存在已经配对过的蓝牙设备
//                        Log.e(TAG, "No can be matched to use bluetooth");
//                    }
//                    //discoveryDevices();
//                }

                discoveryDevices();
                break;
            case R.id.btn_blth_visiblity:
                mBluetoothAdapter.setName("bluetooth new name");
                if (mBluetoothAdapter.isEnabled()) {
                    if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                        Intent discoveryIntent = new Intent(
                                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                        discoveryIntent.putExtra(
                                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                        startActivity(discoveryIntent);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.bluetooth_unopened), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_blth_disconnect:
                if (mBlthChatUtil.getState() != BluetoothChatUtil.STATE_CONNECTED) {
                    Toast.makeText(mContext, "蓝牙未连接", Toast.LENGTH_SHORT).show();
                } else {
                    mBlthChatUtil.stop();
                }
                break;
            case R.id.btn_sendmessage:
//                String messagesend = mEdttMessage.getText().toString();
//                if (null == messagesend || messagesend.length() == 0) {
//                    return;
//                }
//                Log.e(TAG, "sendmessage : " + messagesend);
//                byte[] sendByte = HexCommandtoByte(messagesend.getBytes());
                //mBlthChatUtil.write(messagesend.getBytes());
                mBlthChatUtil.write(getMessage("0x00"));
                mBlthChatUtil.write(getMessage("0x01"));
                break;
            default:
                break;
        }
    }

    //0x00-设置，0x01-启动，0x02-启动，0x03-查询，
    //0x04-停止
    private byte[] getMessage(String flag) {

        String electricity = "75";
        String electricityTwo = "5";
        String load = "5";
        String floorLoad = "2.5";
        String level = "0x04";
        String cos = "0.8";

        String ID = "0x01";
        String sn = "0x01";
        String snType = "0x03";
        String list = "0x56";
        String sFlag = flag;
        String Accuracy = level;
        String Primary = bin2hex(electricity);
        String Secondary = bin2hex(electricityTwo);
        String Rated = bin2hex(load);
        String burden = bin2hex(floorLoad);
        String scos = bin2hex(cos);
        String Check = "0x01";

        String head = "0x5AA5";


        String content = ID + sn + snType + list + sFlag + Accuracy + Primary + Secondary + Rated + burden + scos + Check;

//        byte[] body = content.getBytes(Charset.defaultCharset());
        String end = "0x96";
        String length = "0x98";

//        ByteBuffer bb = ByteBuffer.allocate(2 + body.length);
//        bb.order(ByteOrder.BIG_ENDIAN);
//        bb.putInt(2, body.length);
//        bb.put(body);
//        bb.get();
        String result = head + length + content + end;
        return HexCommandtoByte(result.getBytes());
    }

    /**
     * 合并byte数组
     */
    public static byte[] unitByteArray(byte[] byte1, byte[] byte2) {
        byte[] unitByte = new byte[byte1.length + byte2.length];
        System.arraycopy(byte1, 0, unitByte, 0, byte1.length);
        System.arraycopy(byte2, 0, unitByte, byte1.length, byte2.length);
        return unitByte;
    }

    /**
     * 字符串转换成十六进制值
     *
     * @param bin String 我们看到的要转换成十六进制的字符串
     * @return
     */
    public static String bin2hex(String bin) {
        char[] digital = "0123456789ABCDEF".toCharArray();
        StringBuffer sb = new StringBuffer("");
        byte[] bs = bin.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(digital[bit]);
            bit = bs[i] & 0x0f;
            sb.append(digital[bit]);
        }
        return sb.toString();
    }

    //  十六进制的字符串转换成byte数组
    public static byte[] HexCommandtoByte(byte[] data) {
        if (data == null) {
            return null;
        }
        int nLength = data.length;

        String strTemString = new String(data, 0, nLength);
        String[] strings = strTemString.split(" ");
        nLength = strings.length;
        data = new byte[nLength];
        for (int i = 0; i < nLength; i++) {
            if (strings[i].length() != 2) {
                data[i] = 00;
                continue;
            }
            try {
                data[i] = (byte) Integer.parseInt(strings[i], 16);
            } catch (Exception e) {
                data[i] = 00;
                continue;
            }
        }
        return data;
    }

    private void discoveryDevices() {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        if (mBluetoothAdapter.isDiscovering()) {
            //如果正在扫描则返回
            return;
        }
        mProgressDialog.setTitle(getResources().getString(R.string.progress_scaning));
        mProgressDialog.show();
        // 扫描蓝牙设备
        mBluetoothAdapter.startDiscovery();

    }

    public static String bytesToHexString(byte[] bytes) {
        String result = "";
        for (int i = 0; i < bytes.length; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }

    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "mBluetoothReceiver action =" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //获取蓝牙设备
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (scanDevice == null) return;
                Log.d(TAG, "scan name=" + scanDevice.getName() + "address=" + scanDevice.getAddress());
                //蓝牙设备名称
                String name = scanDevice.getName();
                String address = scanDevice.getAddress();
                if (address != null && address.startsWith("98")) {
                    mBluetoothAdapter.cancelDiscovery();
                    mProgressDialog.setTitle(getResources().getString(R.string.progress_connecting));
                    mBlthChatUtil.connect(scanDevice);
                    Toast.makeText(mContext, "连接成功 in mBluetoothReceiver", Toast.LENGTH_SHORT).show();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

            }
        }

    };
}
